<template>
  <div class="form-variable-container" v-if="config && config.formDefinition">
    <a-input-search v-model="searchText" placeholder="请输入名称" style="height: fit-content; margin: 5px 0"/>
    <select size="10" v-model="selectedVariableName">
      <option @dblclick="() => addVariable(item)"
              v-for="item in searchDataSource" :value="item.variableName">
        {{ item.title }}
      </option>
    </select>
  </div>
</template>
<script>
import {createProps} from '@/utils';
import {getFormDefinitionVariables} from '@comp/hhd/design/FormDesigner/types';

export default {
  name: 'FormVariableContainer',
  props: {
    config: createProps(Object, () => ({
      formDefinition: undefined,
      formIds: undefined,
      prefix: undefined
    }))
  },
  data() {
    return {
      selectedVariableName: undefined,
      searchText: undefined
    };
  },
  methods: {
    selectVariableChange() {
      console.log('selectVariableChange');
    },
    addVariable(variable) {
      variable = JSON.parse(JSON.stringify(variable));
      variable.variableName = (this.config && this.config.prefix || '') + variable.variableName;
      this.$emit('addVariable', variable);
    },
  },
  watch: {
    selectedVariableName() {
      let variable = (this.dataSource || []).find(item => item.variableName === this.selectedVariableName);
      this.$emit('selectVariable', variable);
    },
  },
  computed: {
    searchDataSource() {
      if (!this.searchText) return this.dataSource;
      return this.dataSource.filter(item => (item.title + '').indexOf(this.searchText) !== -1);
    },
    dataSource() {
      if (!this.config || !this.config.formDefinition) return [];
      let res = getFormDefinitionVariables(this.config.formDefinition) || [];
      res = res.filter(item => {
        if (item.formId === (this.config && this.config.formDefinition && this.config.formDefinition.id)) return true;
        let formId = item.formId + '';
        let formIds = this.config && this.config.formIds || '';
        if (formIds.indexOf(formId) !== -1) return true;

        return false;
      });
      return res;
    },
  }
};
</script>
<style>
.form-variable-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.form-variable-container select {
  flex: 1;
  outline: none;
  border: 1px solid #d9d9d9;
  overflow: auto;
}
</style>